package com.agileai.portal.portlets.list;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletModeException;
import javax.portlet.PortletPreferences;
import javax.portlet.ProcessAction;
import javax.portlet.ReadOnlyException;
import javax.portlet.RenderMode;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.ValidatorException;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.domain.DataRow;
import com.agileai.hotweb.domain.TreeBuilder;
import com.agileai.hotweb.domain.TreeModel;
import com.agileai.portal.driver.Resource;
import com.agileai.portal.driver.common.PortletVariableHelper;
import com.agileai.portal.driver.common.PreferenceException;
import com.agileai.portal.driver.common.PreferencesHelper;
import com.agileai.portal.driver.common.PreferencesWrapper;
import com.agileai.portal.portlets.BaseMashupPortlet;
import com.agileai.portal.portlets.PortletCacheManager;
import com.agileai.util.ListUtil;
import com.agileai.util.StringUtil;

public class TreeDataListPortlet extends BaseMashupPortlet {
	protected static final String newRow = "\r\n";
	
	protected List<String> mulSelectNodeTypes = new ArrayList<String>();
	protected List<String> invisiableCheckBoxIdList = new ArrayList<String>(); 

	@RenderMode(name = "view")
	public void view(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		PortletPreferences preferences =  PreferencesHelper.getPublicPreference(request);
		String height = preferences.getValue("height", null);
		String width = preferences.getValue("width", "");
		String isMultiple = preferences.getValue("isMultiple",null);
		boolean isSetting = StringUtil.isNotNullNotEmpty(height) ;
				
		request.setAttribute("height", height);
		request.setAttribute("width", width);
		request.setAttribute("isMultiple", isMultiple);
		request.setAttribute("portletId", request.getWindowID());
		request.setAttribute("isSetting", String.valueOf(isSetting));
		super.doView(request, response);
	}

	@RenderMode(name = "edit")
	public void edit(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
		String height = preferences.getValue("height", "400");
		String width = preferences.getValue("width", "");
		String isMultiple = preferences.getValue("isMultiple","N");
		String isCascade = preferences.getValue("isCascade", "Y");
		String idSpliter = preferences.getValue("idSpliter", MultiDataListPortlet.DefaultSpliter);
		String dataURL = preferences.getValue("dataURL", null);
		String defaultVariableValues = preferences.getValue("defaultVariableValues", null);
		String isCache = preferences.getValue("isCache", defaultIsCache);
		String cacheMinutes = preferences.getValue("cacheMinutes", defaultCacheMinutes);
		String someProperty = preferences.getValue("someProperty", null);
		
		request.setAttribute("height", height);
		request.setAttribute("width", width);
		request.setAttribute("isMultiple", isMultiple);
		request.setAttribute("isCascade", isCascade);
		request.setAttribute("idSpliter", idSpliter);
		request.setAttribute("dataURL", dataURL);
		request.setAttribute("defaultVariableValues", defaultVariableValues);
		request.setAttribute("isCache", isCache);
		request.setAttribute("cacheMinutes", cacheMinutes);
		request.setAttribute("someProperty", someProperty);
				
		super.doEdit(request, response);
	}

	@ProcessAction(name = "saveConfig")
	public void saveConfig(ActionRequest request, ActionResponse response)
			throws ReadOnlyException, PortletModeException, ValidatorException,
			IOException, PreferenceException {
		String height = request.getParameter("height");
		String width = request.getParameter("width");
		String isMultiple = request.getParameter("isMultiple");
		String idSpliter = request.getParameter("idSpliter");
		String isCascade = request.getParameter("isCascade");
		
		String dataURL = request.getParameter("dataURL");
		String defaultVariableValues = request.getParameter("defaultVariableValues");
		String isCache = request.getParameter("isCache");
		String cacheMinutes = request.getParameter("cacheMinutes");
		String someProperty = request.getParameter("someProperty");

		PreferencesWrapper preferWapper = new PreferencesWrapper();		
		preferWapper.setValue("height", height);
		preferWapper.setValue("width", width);
		preferWapper.setValue("isMultiple", isMultiple);
		preferWapper.setValue("isCascade", isCascade);
		preferWapper.setValue("idSpliter", idSpliter);
		preferWapper.setValue("defaultVariableValues", defaultVariableValues);
		preferWapper.setValue("dataURL", dataURL);
		preferWapper.setValue("isCache", isCache);
		preferWapper.setValue("cacheMinutes", cacheMinutes);
		preferWapper.setValue("someProperty", someProperty);
		
		PreferencesHelper.savePublicPreferences(request, preferWapper.getPreferences());	
		response.setPortletMode(PortletMode.VIEW);
	}
	@Resource(id="getAjaxData")
	public void getAjaxData(ResourceRequest request, ResourceResponse response)
			throws PortletException, IOException {
		String ajaxData = "";
		StringBuffer treeSyntax = new StringBuffer();
		String scriptSyntax = "";
		try {
			PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
			String cacheMinutes = (String)preferences.getValue("cacheMinutes",defaultCacheMinutes);
			String isCache = preferences.getValue("isCache", defaultIsCache);
			String dataURL = getDataURL(request);
			ajaxData = PortletCacheManager.getOnly().getCachedData(isCache, dataURL, cacheMinutes);
			
			String isMultiple = preferences.getValue("isMultiple",null);
			List<DataRow> records = this.parseRecords(ajaxData);
	        TreeBuilder treeBuilder = new TreeBuilder(records, "id","name", "parentId");
	        TreeModel topTreeModel = treeBuilder.buildTreeModel();
        	
	        PortletVariableHelper variableHelper = new PortletVariableHelper(request);
	        String listItemKey = variableHelper.getDefaultValue(dataURL,"listItemKey");
	        if ("Y".equals(isMultiple)){
	        	String isCascade = preferences.getValue("isCascade", "Y");
	        	String idSpliter = preferences.getValue("idSpliter", MultiDataListPortlet.DefaultSpliter);
	        	scriptSyntax = this.getMuliPickTreeSyntax(topTreeModel, treeSyntax,isCascade,idSpliter,listItemKey);
	        }else{
	        	scriptSyntax = this.getTreeSyntax(topTreeModel, treeSyntax,listItemKey);
	        }
	        
		} catch (Exception e) {
			this.logger.error("获取取数据失败getAjaxData", e);
		}
        
		PrintWriter writer = response.getWriter();
		writer.print(scriptSyntax);
		writer.close();
	}
	
	private List<DataRow> parseRecords(String ajaxData) throws JSONException{
		List<DataRow> result = new ArrayList<DataRow>();
		JSONArray jsonArray = new JSONArray(ajaxData);
		for (int i=0;i < jsonArray.length();i++){
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			DataRow row = new DataRow();
			row.put("id",jsonObject.get("id"));
			row.put("name",jsonObject.get("name"));
			row.put("parentId",jsonObject.get("parentId"));
			result.add(row);
		}
		return result;
	}
	
	protected String getTreeSyntax(TreeModel treeModel,StringBuffer treeSyntax,String listItemKey){
    	String result = null;
    	try {
    		treeSyntax.append("d = new dTree('d');").append(newRow);
            String rootId = treeModel.getId();
            String rootName = treeModel.getName();
            treeSyntax.append("d.add('"+rootId+"',-1,'"+rootName+"',\"javascript:doAjaxRefreshPortalPage('"+listItemKey+":"+rootId+"')\");").append(newRow);
            buildTreeSyntax(treeSyntax,treeModel,listItemKey);
           // treeSyntax.append("document.write(d);");
    		result = treeSyntax.toString();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
    }
	
	
	
	protected void buildTreeSyntax(StringBuffer treeSyntax,TreeModel treeModel,String listItemKey){
		List<TreeModel> children = treeModel.getChildren();
		String parentId = treeModel.getId();
        for (int i=0;i < children.size();i++){
        	TreeModel child = children.get(i);
            String curNodeId = child.getId();
            String curNodeName = child.getName();
            if (!ListUtil.isNullOrEmpty(child.getChildren())){
            	treeSyntax.append("d.add('"+curNodeId+"','"+parentId+"','"+curNodeName+"',\"javascript:doAjaxRefreshPortalPage('"+listItemKey+":"+curNodeId+"')\");").append(newRow);
            }else{
            	treeSyntax.append("d.add('"+curNodeId+"','"+parentId+"','"+curNodeName+"',\"javascript:doAjaxRefreshPortalPage('"+listItemKey+":"+curNodeId+"')\");").append(newRow);
            }
            this.buildTreeSyntax(treeSyntax,child,listItemKey);
        }
    }    
	
	protected String getMuliPickTreeSyntax(TreeModel topTreeModel,StringBuffer treeSyntax,String isCascade,String idSpliter,String listItemKey){
    	String result = null;
    	try {
    		treeSyntax.append("tv.checkCallBack = function(){").append(newRow);
//			treeSyntax.append("	 alert(this.getSelectedIds('").append(idSpliter).append("'));").append(newRow);
			treeSyntax.append("	 var selecteIds = this.getSelectedIds('").append(idSpliter).append("');").append(newRow);
			treeSyntax.append("	 doAjaxRefreshPortalPage('"+listItemKey+":'+selecteIds);").append(newRow);
			treeSyntax.append("}").append(newRow);
    		
			boolean checkRelChildren = "Y".equals(isCascade);
			
    		treeSyntax.append("tree = new sTree();").append(newRow);
    		treeSyntax.append("tree.setImagePath('/portal_portlets/images/stree/');").append(newRow);
    		treeSyntax.append("tree.checkRelChildren = ").append(String.valueOf(checkRelChildren)).append(";").append(newRow);
            String rootId = topTreeModel.getId();
            String rootName = topTreeModel.getName();
            String nodeType = topTreeModel.getType();
            boolean hasCheckBox = !invisiableCheckBoxIdList.contains(rootId);
            
            if (mulSelectNodeTypes.isEmpty()){
            	treeSyntax.append("tree.add('"+rootId+"','0','"+rootName+"','javascript:void(0)',Icon.root.src,"+String.valueOf(hasCheckBox)+");").append(newRow);            	
            }else{
            	if (mulSelectNodeTypes.contains(nodeType)){
            		treeSyntax.append("tree.add('"+rootId+"','0','"+rootName+"','javascript:void(0)',Icon.root.src,"+String.valueOf(hasCheckBox)+");").append(newRow);	
            	}else{
            		treeSyntax.append("tree.add('"+rootId+"','0','"+rootName+"','javascript:void(0)',Icon.root.src,false);").append(newRow);            		
            	}
            }
            buildMultiPickTreeSyntax(topTreeModel,treeSyntax);
            treeSyntax.append("tree.setName='selectTree';").append(newRow);
//            treeSyntax.append("tree.drawTree('selectTreeContainer');");
    		result = treeSyntax.toString();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
    }
	protected void buildMultiPickTreeSyntax(TreeModel treeModel,StringBuffer treeSyntax){
    	List<TreeModel> arrayList = treeModel.getChildren();
    	String pId = treeModel.getId();
        for (int i=0;i < arrayList.size();i++){
        	TreeModel curTreeModel = arrayList.get(i);
            String curId = curTreeModel.getId();
            String curName = curTreeModel.getName();
            String curType = curTreeModel.getType();
            boolean hasCheckBox = !invisiableCheckBoxIdList.contains(curId);
            if (mulSelectNodeTypes.isEmpty()){
            	treeSyntax.append("tree.add('"+curId+"','"+pId+"','"+curName+"','javascript:void(0)',null,"+String.valueOf(hasCheckBox)+");").append(newRow);
            }else{
                if (mulSelectNodeTypes.contains(curType)){
                	treeSyntax.append("tree.add('"+curId+"','"+pId+"','"+curName+"','javascript:void(0)',null,"+String.valueOf(hasCheckBox)+");").append(newRow);
                }else{
                	treeSyntax.append("tree.add('"+curId+"','"+pId+"','"+curName+"','javascript:void(0)',null,false);").append(newRow);
                }            	
            }
            this.buildMultiPickTreeSyntax(curTreeModel,treeSyntax);
        }
    }    
}
